<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;

class Tickets extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'tickets';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'payment_time_text'
    ];
    

    
    public static function getCode($prefix = '')
    {
        // $code = mt_rand(1000000000, 9999999999);
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $chars = "0123456789";
        mt_srand(10000000 * (float)microtime());
        for ($i = 0, $code = $prefix, $lc = strlen($chars) - 1; $i < 7 - strlen($prefix); $i++) {
            $code .= $chars[mt_rand(0, $lc)];
        }
        if (self::where('card_number', $code)->find()) {   //如果已经存在核销码，则从新随机获取
            return self::getCode();
        }
        return $code;
    }


    public function getPaymentTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payment_time']) ? $data['payment_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaymentTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

}
